# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging

logger = logging.getLogger()

from piHAlibs import (my_fctname,coroutine)
try:
    from .rfxtrxlibs import (RFXTRXParsers,TRXUNDParsers)
except ImportError as e:
    logger.critical("%s : %s", repr(e.__class__), str(e))
    print ('RFXtrx modules not yet installed')


def valueofmsg(item,pair):
    msg = item.split(';')
    for pv in msg:
         if pair in pv:
              return pv.split(':')[1]

def item2msgs(item):
    if not item[1].startswith('0x') : return None
    namedev = item[0]
    if 'RFXTRX' not in namedev : return None
    a = item[1].split()
    if len(a) < 5 : return None
    hdlen = a[0]
    type = a[1]
    subtype = a[2]
    seqnb = a[3]
    data = a[4:]
    p = [ int(i,16) for i in data ]
    return [namedev,type,subtype,data, p, hdlen,item[1]]


@my_fctname
@coroutine
def RFXTRXparser(decoders,rejected=None):
    """
    item = [namedev,events]
    split events (if several) before sending to RFXTRXparser1
    """
    while True:
        events = (yield)
        logger.debug("Event receive %s",repr(events))
        evts = events[1].split('|')
        if len(evts) > 1:
            for event in evts:
                RFXTRXparser1(decoders,rejected=None).send([events[0],event])
        else:
            RFXTRXparser1(decoders,rejected=None).send(events)


@my_fctname
@coroutine
def RFXTRXparser1(decoders,rejected=None):
    """
    Parse protocol model for RFXtrx433 Controller
    item = [namedev,event]
    Send to next target = decoder if undecoded
    """
    hdu = TRXUNDParsers
    hdps = RFXTRXParsers
    while True:
        item = (yield)
        logger.debug("Event receive %s",repr(item))
        msgs = item2msgs(item)
        if not msgs : continue
        namedev,type,subtype,data, p, hdlen,revt = msgs
        logger.debug("%s",repr(msgs))
        if type in ('0x00','0x01','0x02'): continue
        V = (hdlen,type,subtype)
        if type == '0x03' and rejected:
            if subtype in hdu:
                logger.debug("Data undecoded %s",repr(msgs))
                rejected.send(msgs)
            continue
        elif V not in hdps:
            if rejected: rejected.send(['NEW_PROTRX',hdlen,type,subtype] + item)
            continue
        msgs[5] =  hdps[V][0]   #protocol
        msgs.append(hdps[V][2]) #decoder row
        logger.debug("Data to decode %s",repr(msgs))
        for target in decoders:
            logger.debug("Data sent to %s",repr(target))
            target.send(msgs)
